package co.za.itweb.itwebpro;



import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.ConfigurationBuilder;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import co.za.itweb.itwebpro.SimpleGestureFilter.SimpleGestureListener;


@SuppressLint("ParserError")
public class SearchedNews extends Activity implements SimpleGestureListener {
	HorizontalScrollView Hlv;
	LinearLayout linear;
	private SimpleGestureFilter detector;
	private LayoutInflater inflater;
	private InputStream is;
	private String result;
	private JSONObject jArray;
	static String tinyurl;
	private String bigImage;
	private String tITLE;
	int positionX;
	private View[] view;
	private ImageView[] newsview;
	private TextView[] text;
	private TextView[] title;
	private LinearLayout[] insertIt;
	private RelativeLayout[] relativeLay;
	private static int offsetX;
	private ListView singlelist;
	private SingleAdapter singleAdapter;
	static ViewFlipper FLIP;
	TextView newsTitleText;
	private String TextauthorName;
	String itemID;
	NewsFetcher NF;
	private TextView TextAuthor;
	private String introText;
	private String section;
	private int CurrentITEMID;
	private String CurrentSECTION;
	public String link;
	public String disqus = "false";
	public String storyText;
	private TextView Story;
	public String Date;
	private TextView DateText;
	private int newscounter = 0;
	ViewHolder VH;
	ViewItems VI = null;
	SeekBar seek;
	private Animation animFlipInForeward;
	private Animation animFlipOutForeward;
	private Animation animFlipInBackward;
	private Animation animFlipOutBackward;
	private String titlefeed;
	//static int discrete=15;
	int start = 0;
	int end = 10;
	int start_pos = 0;
	int start_position = 0;
	int baseTextSize;
	
	private TextView StoryInflated;
	private co.za.itweb.itwebpro.QuickAction mQuickAction;
	private static final int FAVORITE = 1;
	private static final int TWITTER = 2;
	private static final int EMAIL = 3;
	int feed;
	static boolean logged = false;
	public String accessToken;
	public String accessTokenSecret;
	TweetTask tt;
	ResumeTask rt;
	UpdateTask ut;
	public Twitter mTwitter;
	public boolean haveConnectedWifi;
	public boolean haveConnectedMobile;
	String oauthVerifier;
	public int TWITTER_AUTH = 55;
	public RequestToken mRequestToken;
	private boolean tweeted = false;
	private String website;
	private String loginCheck;
	private String density2;
	private int width;
	private int bannerHolderWidth2;
	private WebView myWebView;
	private WebView banner;
	private String mainfolder;
	private ImageButton fontbut;
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.single_item);
		VH = new ViewHolder();

		Bundle extras = getIntent().getExtras();
		feed = extras.getInt("feed");
		itemID = extras.getString("itemID");
		section = extras.getString("section");
		if (savedInstanceState == null) {

			positionX = extras.getInt("position");
			CurrentITEMID = Integer.parseInt(itemID);
			CurrentSECTION = section;
			titlefeed = extras.getString("titlefeed");

		} else {
			positionX = savedInstanceState.getInt("list_state");
			CurrentITEMID = savedInstanceState.getInt("CURRENTITEMID");
			CurrentSECTION = savedInstanceState.getString("CURRENTSECTION");
			titlefeed = savedInstanceState.getString("CURRENTTITLE");

		}

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);

		width = metrics.widthPixels;
		if (width <= 250) {
			mainfolder = "240";

		} else if (width > 250 && width <= 320) {
			mainfolder = "320";

		} else if (width > 320 && width <= 480) {
			mainfolder = "480";

		} else if (width > 480 && width <= 720) {
			mainfolder = "720";
		} else if (width > 720 && width <= 800) {
			mainfolder = "800";
		} else if (width > 800 && width <= 1280) {
			mainfolder = "1280";
		} else {
			mainfolder = "1280";
		}

		detector = new SimpleGestureFilter(this, this);

		Button back = (Button) findViewById(R.id.back);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		

		final String[] itemid = new String[SearchActivity.List.get(feed)._itemlist
				.size()];
		String[] titles = new String[SearchActivity.List.get(feed)._itemlist
				.size()];
		String[] images = new String[SearchActivity.List.get(feed)._itemlist
				.size()];
		String[] bigimages = new String[SearchActivity.List.get(feed)._itemlist
				.size()];
		String[] story = new String[SearchActivity.List.get(feed)._itemlist
				.size()];
		String[] published = new String[SearchActivity.List.get(feed)._itemlist
				.size()];
		String[] summary = new String[SearchActivity.List.get(feed)._itemlist
				.size()];
		String[] author = new String[SearchActivity.List.get(feed)._itemlist
				.size()];

		for (int y = 0; y < SearchActivity.List.get(feed)._itemlist.size(); y++) {
			itemid[y] = SearchActivity.List.get(feed)._itemlist.get(y)
					.getItemId();
			titles[y] = SearchActivity.List.get(feed)._itemlist.get(y).getTitle();
			images[y] = SearchActivity.List.get(feed)._itemlist.get(y)
					.getIntroImage();
			summary[y] = SearchActivity.List.get(feed)._itemlist.get(y)
					.getIntroText();

		}
		inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		TextView titleFEED = (TextView) findViewById(R.id.newstitle);
		titleFEED.setText(titlefeed);
		fontbut = (ImageButton)findViewById(R.id.fontresizer);
		fontbut.setOnClickListener(new OnClickListener(){
			

			@Override
			public void onClick(View v) {
				Intent intenty = new Intent(SearchedNews.this,
						FontDialog.class);
				intenty.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivityForResult(intenty,77);
				
			}
		});

		ActionItem addToFavs = new ActionItem(FAVORITE, "Add to favorites",
				getResources().getDrawable(R.drawable.star_gold));
		ActionItem tweet = new ActionItem(TWITTER, "Tweet", getResources()
				.getDrawable(R.drawable.twitter));
		ActionItem email = new ActionItem(EMAIL, "Email to friend",
				getResources().getDrawable(R.drawable.email));
		mQuickAction = new QuickAction(getApplicationContext(),
				QuickAction.VERTICAL);

		mQuickAction.addActionItem(addToFavs);

		mQuickAction.addActionItem(tweet);

		mQuickAction.addActionItem(email);

		Button share = (Button) findViewById(R.id.share);
		share.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mQuickAction.show(v);
				mQuickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_RIGHT);
			}
		});

		tt = new TweetTask(this);
		rt = new ResumeTask();
		ut = new UpdateTask(this);

		SharedPreferences settings = PreferenceManager
				.getDefaultSharedPreferences(SearchedNews.this);
		accessToken = settings.getString("twitter_access_token", null);
		accessTokenSecret = settings.getString("twitter_access_token_secret",
				null);

		mQuickAction
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {

					@Override
					public void onItemClick(QuickAction quickAction, int pos,
							int actionId) {

						if (actionId == FAVORITE) {
							if (checkFavorite()) {

								
								Toast.makeText(getApplicationContext(),
										"Already in favourites",
										Toast.LENGTH_SHORT).show();
							} else {
								if (addFavorite()) {
									Toast.makeText(getApplicationContext(),
											"Added to favourites",
											Toast.LENGTH_SHORT).show();
									quickAction.getActionItem(pos).setIcon(
											getResources().getDrawable(
													R.drawable.star_black));

								} else {
									Toast.makeText(
											getApplicationContext(),
											"There has been a mistake, please try again",
											Toast.LENGTH_SHORT).show();
								}
							}

						} else if (actionId == TWITTER) {
							if (tweeted == false) {
								if (accessToken == null
										|| accessToken.length() < 2) {
									tt.execute();

								} else {

									ut.execute();

								}
							}

						} else if (actionId == EMAIL) {
							final Intent emailIntent = new Intent(
									android.content.Intent.ACTION_SEND);
							emailIntent.setType("plain/text");
							emailIntent.putExtra(
									android.content.Intent.EXTRA_EMAIL,
									new String[] { "" });
							emailIntent.putExtra(
									android.content.Intent.EXTRA_SUBJECT,
									"ITWeb PRO article - "
											+ newsTitleText.getText());
							emailIntent.putExtra(
									android.content.Intent.EXTRA_TEXT, link);

							startActivity(Intent.createChooser(emailIntent,
									"Send email..."));

						} else {

						}
					}
				});

		mQuickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
			@Override
			public void onDismiss() {

			}
		});

		FLIP = (ViewFlipper) findViewById(R.id.flipper);

		animFlipInForeward = AnimationUtils.loadAnimation(this, R.anim.flipin);
		animFlipOutForeward = AnimationUtils
				.loadAnimation(this, R.anim.flipout);
		animFlipInBackward = AnimationUtils.loadAnimation(this,
				R.anim.flipin_reverse);
		animFlipOutBackward = AnimationUtils.loadAnimation(this,
				R.anim.flipout_reverse);
		Hlv = (HorizontalScrollView) findViewById(R.id.horizon);
		singlelist = (ListView) findViewById(R.id.verticalsingleitemlist);
		singlelist.setClickable(true);

		ViewTreeObserver viewTreeObserver = Hlv.getViewTreeObserver();
		if (viewTreeObserver.isAlive()) {
			viewTreeObserver
					.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
						@Override
						public void onGlobalLayout() {
							View oldView = Hlv.findViewWithTag(1111);
							if (oldView != null) {
								int offsetX2 = ((oldView.getLeft() + oldView
										.getRight()) / 2)
										- (Hlv.getWidth() / 2);

								oldView.setTag(111111111);

								Hlv.smoothScrollTo(offsetX2, 0);
							}
						}
					});
		}

		if (isXLargeScreen(getApplicationContext())
				&& getOrientation(getApplicationContext()) == "landscape") {// /////////////////////////////////////////////////////////////////////////////////

			singlelist.setVisibility(View.GONE);

			linear = (LinearLayout) findViewById(R.id.horisontalcontainer);
			view = new View[titles.length];
			newsview = new ImageView[titles.length];
			text = new TextView[titles.length];
			title = new TextView[titles.length];
			insertIt = new LinearLayout[titles.length];
			relativeLay = new RelativeLayout[titles.length];
			for (int h = 0; h < titles.length; h++) {
				view[h] = inflater.inflate(R.layout.imageslist_single, null);
				relativeLay[h] = (RelativeLayout) view[h]
						.findViewById(R.id.myparent);
				insertIt[h] = (LinearLayout) findViewById(R.id.horisontalcontainer);
				title[h] = (TextView) view[h].findViewById(R.id.TextOnImage);
				text[h] = (TextView) view[h].findViewById(R.id.TextTitle);
				newsview[h] = (ImageView) view[h].findViewById(R.id.oneimage);
				if (images[h].length() > 4) {

					LazyLoadImage icondownloader = new LazyLoadImage(
							newsview[h]);

					Bitmap avatar = icondownloader
							.getBitmapFromCache(SearchActivity.cachedir+"/"
									+ images[h]);

					if (avatar == null) {
						icondownloader
								.execute(SearchActivity.cachedir+"/"
										+ images[h]);

					} else {

						newsview[h].setImageBitmap(avatar);
					}

					title[h].setText(titles[h]);
					text[h].setVisibility(View.GONE);
				} else {
					newsview[h].setBackgroundColor(Color
							.parseColor("#ff050505"));
					if (summary[h].length() > 90) {
						String it = summary[h].substring(0, 90);
						it = it + "...";
						title[h].setText(it);
					} else {
						title[h].setText(summary[h]);
					}

					title[h].setHeight(250);

					text[h].setText(titles[h]);
					text[h].setTypeface(null, Typeface.BOLD);

				}

				view[h].setId(Integer.parseInt(itemid[h]));

				if (h == positionX) {
					RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
							RelativeLayout.LayoutParams.MATCH_PARENT,
							RelativeLayout.LayoutParams.MATCH_PARENT);

					relativeLay[h].setBackgroundColor(Color
							.parseColor("#ff376ccd"));
					relativeLay[h].setLayoutParams(lp);

					view[h].setTag(1111);
					if (NF != null) {
						if (NF.getStatus() == AsyncTask.Status.RUNNING) {
							NF.cancel(true);
						}
					}
					NF = new NewsFetcher(CurrentITEMID, SearchedNews.this);
					NF.execute();

				}

				final int pos = h;
				view[h].setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						CurrentITEMID = arg0.getId();

						if (NF.getStatus() == AsyncTask.Status.RUNNING) {
							NF.cancel(true);
						}
						NF = new NewsFetcher(CurrentITEMID, SearchedNews.this);
						NF.execute();

						for (int l = 0; l < view.length; l++) {

							view[l].setBackgroundColor(Color
									.parseColor("#ff050505"));
						}

						View oldView = arg0.findViewWithTag(1111);
						if (oldView != null) {
							oldView.setBackgroundColor(Color
									.parseColor("#ff050505"));
							oldView.setTag("111111111");
						}
						arg0.setBackgroundColor(Color.parseColor("#ff376ccd"));

						int offsetX2 = ((arg0.getLeft() + arg0.getRight()) / 2)
								- (Hlv.getWidth() / 2);

						positionX = pos;
						Hlv.smoothScrollTo(offsetX2, 0);

					}

				});
				insertIt[h].addView(view[h]);

			}

		} else if (isXLargeScreen(getApplicationContext())
				&& getOrientation(getApplicationContext()) == "portrait") {// /////////////////////////////////////////////////////////////////////////////////////
			Hlv = (HorizontalScrollView) findViewById(R.id.horizon);
			Hlv.setVisibility(View.GONE);

			singlelist.setVisibility(View.VISIBLE);

			singleAdapter = new SingleAdapter(this, itemid, titles, images,
					summary);

			singlelist.setAdapter(singleAdapter);
			singleAdapter.notifyDataSetChanged();
			singlelist.setSelection(positionX);
			if (NF != null) {
				if (NF.getStatus() == AsyncTask.Status.RUNNING) {
					NF.cancel(true);
				}
			}
			NF = new NewsFetcher(CurrentITEMID, SearchedNews.this);
			NF.execute();

			singlelist.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					CurrentITEMID = arg1.getId();
					if (NF.getStatus() == AsyncTask.Status.RUNNING) {
						NF.cancel(true);
					}
					NF = new NewsFetcher(CurrentITEMID, SearchedNews.this);
					NF.execute();

					for (int x = 0; x < singlelist.getChildCount(); x++) {
						singlelist.getChildAt(x).setBackgroundColor(
								Color.parseColor("#ff050505"));
					}
					arg1.setBackgroundColor(Color.parseColor("#ff376ccd"));

					positionX = arg2;
					singlelist.setSelection(arg2);

				}

			});

		} else if (!isXLargeScreen(getApplicationContext())) {// ///////////////////////////////////////////////////////////////////////////////
			singlelist.setVisibility(View.GONE);

			linear = (LinearLayout) findViewById(R.id.horisontalcontainer);
			view = new View[titles.length];
			newsview = new ImageView[titles.length];
			text = new TextView[titles.length];
			title = new TextView[titles.length];
			insertIt = new LinearLayout[titles.length];
			relativeLay = new RelativeLayout[titles.length];

			for (int h = 0; h < titles.length; h++) {
				view[h] = inflater.inflate(R.layout.imageslist_single, null);
				relativeLay[h] = (RelativeLayout) view[h]
						.findViewById(R.id.myparent);
				insertIt[h] = (LinearLayout) findViewById(R.id.horisontalcontainer);
				title[h] = (TextView) view[h].findViewById(R.id.TextOnImage);
				text[h] = (TextView) view[h].findViewById(R.id.TextTitle);
				newsview[h] = (ImageView) view[h].findViewById(R.id.oneimage);

				if (images[h].length() > 4) {

					LazyLoadImage icondownloader = new LazyLoadImage(
							newsview[h]);

					Bitmap avatar = icondownloader
							.getBitmapFromCache(MainActivity.cachedir+"/"
									+ images[h]);

					if (avatar == null) {
						icondownloader
								.execute(MainActivity.cachedir+"/"
										+ images[h]);

					} else {

						newsview[h].setImageBitmap(avatar);
					}

					title[h].setText(titles[h]);
					text[h].setVisibility(View.GONE);
				} else {
					newsview[h].setBackgroundColor(Color
							.parseColor("#ff050505"));
					if (summary[h].length() > 90) {
						String it = summary[h].substring(0, 90);
						it = it + "...";
						title[h].setText(it);
					} else {
						title[h].setText(summary[h]);
					}

					title[h].setHeight(250);

					text[h].setText(titles[h]);
					text[h].setTypeface(null, Typeface.BOLD);

				}

				view[h].setId(Integer.parseInt(itemid[h]));

				if (h == positionX) {
					RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
							RelativeLayout.LayoutParams.MATCH_PARENT,
							RelativeLayout.LayoutParams.MATCH_PARENT);

					relativeLay[h].setBackgroundColor(Color
							.parseColor("#ff376ccd"));
					relativeLay[h].setLayoutParams(lp);

					view[h].setTag(1111);
					if (NF != null) {
						if (NF.getStatus() == AsyncTask.Status.RUNNING) {
							NF.cancel(true);
						}
					}
					NF = new NewsFetcher(CurrentITEMID, SearchedNews.this);
					NF.execute();

				}

				final int pos = h;
				view[h].setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						CurrentITEMID = arg0.getId();

						if (NF.getStatus() == AsyncTask.Status.RUNNING) {
							NF.cancel(true);
						}
						NF = new NewsFetcher(CurrentITEMID, SearchedNews.this);
						NF.execute();

						for (int l = 0; l < view.length; l++) {

							view[l].setBackgroundColor(Color
									.parseColor("#ff050505"));
						}

						View oldView = arg0.findViewWithTag(1111);
						if (oldView != null) {
							oldView.setBackgroundColor(Color
									.parseColor("#ff050505"));
							oldView.setTag("111111111");
						}
						arg0.setBackgroundColor(Color.parseColor("#ff376ccd"));

						int offsetX2 = ((arg0.getLeft() + arg0.getRight()) / 2)
								- (Hlv.getWidth() / 2);

						positionX = pos;
						Hlv.smoothScrollTo(offsetX2, 0);

					}

				});
				insertIt[h].addView(view[h]);

			}

		}// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	}

	public static boolean isXLargeScreen(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
	}

	@SuppressWarnings("deprecation")
	public  String getOrientation(Context context) {

		final int rotation = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay().getOrientation();
		switch (rotation) {
		case Surface.ROTATION_0:
			return "portrait";
		case Surface.ROTATION_90:
			return "landscape";
		case Surface.ROTATION_180:
			return "portrait";
		default:
			return "landscape";
		}
	}

	@SuppressLint({ "ParserError", "ParserError" })
	private void showNews() {// ///////////////////////////////////////////////////////////////------------------------------------------------------SHOW
								// NEWS ARTICLE

		if (VI != null) {

			tITLE = VI.getTitle();
			TextauthorName = VI.getJournalist();
			Date = VI.getDate();
			storyText = VI.getText();
			bigImage = VI.getIntroImage();
			VI = null;

		}
		
		View newsInflatedView = inflater.inflate(R.layout.news_layout, null,
				false);
		
		newsTitleText = (TextView) newsInflatedView
				.findViewById(R.id.textarticle);
		TextAuthor = (TextView) newsInflatedView.findViewById(R.id.author);
		Story = (TextView) newsInflatedView.findViewById(R.id.summary);

		DateText = (TextView) newsInflatedView.findViewById(R.id.published);
		newsTitleText.setText(tITLE);
		if (TextauthorName != null && TextauthorName.length() > 3 ) {
			TextAuthor.setText("By: " + TextauthorName);
		}
		if (Date != null) {
			DateText.setText("Published on: " + Date);
		}
		Story.setText(storyText);
		Story.setTextSize(News.discrete);
		ImageView bigImageView = (ImageView) newsInflatedView
				.findViewById(R.id.bigimage);

		LazyLoadImage icondownloader = new LazyLoadImage(bigImageView);
		Bitmap avatar = icondownloader.getBitmapFromCache(bigImage);

		if (avatar == null) {
			icondownloader.execute(bigImage);

		} else {

			bigImageView.setImageBitmap(avatar);
		}

		

		if (disqus.equals("true")) {
			RelativeLayout linLayout = (RelativeLayout) newsInflatedView
					.findViewById(R.id.disquss);

			if (determineDensity() == "ldpi") {
				bannerHolderWidth2 = (int) (int) (width + (width / 3)) - 10;
			} else if (determineDensity() == "mdpi") {
				bannerHolderWidth2 = (int) (width) - 10;
			} else if (determineDensity() == "hdpi") {

				bannerHolderWidth2 = (int) (width - (width / 3)) - 10;

			} else if (determineDensity() == "xdpi") {
				bannerHolderWidth2 = (int) width + (width / 2) - 10;
			}
			RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
					width, LayoutParams.WRAP_CONTENT);

			myWebView = new WebView(SearchedNews.this);
			linLayout.addView(myWebView, layoutParams);

			String articleTITLE = newsTitleText.getText().toString();

			((WebView) myWebView).getSettings().setJavaScriptEnabled(true);

			int currentapiVersion = Build.VERSION.SDK_INT;
			if (currentapiVersion <= Build.VERSION_CODES.GINGERBREAD) {
				System.out.println("Verzija: " + currentapiVersion);
				((WebView) myWebView).setWebViewClient(new WebViewClient() {

				});
				((WebView) myWebView).setWebChromeClient(new WebChromeClient() {
					@Override
					public boolean onJsAlert(WebView view, String url,
							String message, final android.webkit.JsResult result) {
						Toast.makeText(getApplicationContext(), message,
								Toast.LENGTH_SHORT).show();
						result.confirm();
						return true;
					}
				});

				((WebView) myWebView)
						.loadData(
								"<html><head><meta name=\"viewport\" content=\"minimum-scale=1.0; maximum-scale=1.0; user-scalable=false; initial-scale=1.0;\"/><style>html,body,iframe{margin:0;padding:0;}</style></head><body><iframe style=\"width:"
										+ bannerHolderWidth2
										+ "px;height:600px;border:0px;margin:0px;\" src=\"http://itweb.mobi/disqus-comments.php?id="
										+ CurrentITEMID
										+ "&url=source=android&tag=article&id="
										+ CurrentITEMID
										+ "&title="
										+ articleTITLE
										+ "\"></iframe></body></html>",
								"text/html", null);

			} else {
				System.out.println("Verzija TREBALO BI : " + currentapiVersion);
				((WebView) myWebView).setWebViewClient(new WebViewClient() {

				});
				((WebView) myWebView).setWebChromeClient(new WebChromeClient() {
					@Override
					public boolean onJsAlert(WebView view, String url,
							String message, final android.webkit.JsResult result) {
						Toast.makeText(getApplicationContext(), message,
								Toast.LENGTH_SHORT).show();
						result.confirm();
						return true;
					}
				});

				((WebView) myWebView)
						.loadUrl("http://itweb.mobi/disqus-comments.php?id="
								+ CurrentITEMID
								+ "&url=source=android&tag=article&id="
								+ CurrentITEMID + "&title=" + articleTITLE);

			}

		}
		

		RelativeLayout lin = (RelativeLayout) newsInflatedView
				.findViewById(R.id.webbanner);

		if (width >= 728) {
			RelativeLayout.LayoutParams layout = new RelativeLayout.LayoutParams(
					728, RelativeLayout.LayoutParams.WRAP_CONTENT);
			banner = new WebView(SearchedNews.this);
			lin.addView(banner, layout);
		} else {
			RelativeLayout.LayoutParams layout2 = new RelativeLayout.LayoutParams(
					width, RelativeLayout.LayoutParams.WRAP_CONTENT);
			banner = new WebView(SearchedNews.this);
			lin.addView(banner, layout2);
		}

		banner.getSettings().setJavaScriptEnabled(true);

		((WebView) banner).setWebChromeClient(new WebChromeClient() {

		});

		banner.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				if (url != null && url.startsWith("http://")) {
					view.getContext().startActivity(
							new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
					return true;
				} else {
					return false;
				}

			}

		});

		System.out
				.println("http://itweb.mobi/__bottombar/index.php?app=itwebpro&device=android&width="
						+ mainfolder
						+ "&height=50&density="
						+ determineDensity()
						+ "&section="
						+ CurrentSECTION
						+ "<<<<<<<<<");

		banner.loadUrl("http://itweb.mobi/__bottombar/index.php?app=itwebpro&device=android&width="
				+ mainfolder
				+ "&height=50&density="
				+ determineDensity()
				+ "&section=" + CurrentSECTION);

		newsInflatedView.setId(positionX);
		FLIP.addView(newsInflatedView, newscounter);
		FLIP.setDisplayedChild(newscounter);

		newscounter++;
		if (loginCheck !=null && loginCheck.length() > 3 && logged == false) {

			if (checkUserLogin()) {
				logged = true;
			} else {
				Intent intentx = new Intent(getApplicationContext(),
						Login.class);
				intentx.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivityForResult(intentx, 6);
			}

		}

		/*
		 * if(MainActivity.websiteData!=null){ for(int j =
		 * 0;j<MainActivity.webOrder.length();j++){ try {
		 * if(section.contains(MainActivity.webOrder.getString(j))){ tinyurl =
		 * MainActivity
		 * .websiteData.getJSONObject(MainActivity.webOrder.getString
		 * (j)).getString("tinyid"); website =
		 * MainActivity.websiteData.getJSONObject
		 * (MainActivity.webOrder.getString(j)).getString("url"); } } catch
		 * (JSONException e) {
		 * 
		 * e.printStackTrace(); } } }
		 */

	}// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	public String determineDensity() {
		switch (getResources().getDisplayMetrics().densityDpi) {
		case DisplayMetrics.DENSITY_LOW:
			density2 = "ldpi";

			break;
		case DisplayMetrics.DENSITY_MEDIUM:
			density2 = "mdpi";

			break;
		case DisplayMetrics.DENSITY_HIGH:
			density2 = "hdpi";

			break;
		case DisplayMetrics.DENSITY_XHIGH:
			density2 = "xdpi";
			break;
		}
		return density2;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
		if (requestCode == 1) {

			if (resultCode == RESULT_OK) {
				Toast.makeText(getApplicationContext(),
						"News are refreshed...", Toast.LENGTH_SHORT).show();
			}
			if (resultCode == RESULT_CANCELED) {
				finish();
			}
			if (resultCode == 2) {
				Toast.makeText(getApplicationContext(),
						"There is no internet connection..., please try again",
						Toast.LENGTH_SHORT).show();
			}
		}

		if (requestCode == 6) {
			if (resultCode == 222) {

			}
			if (resultCode == 111) {
				Toast.makeText(
						SearchedNews.this,
						"Wrong username / password or subscription expired. You are not authorised to read this article ",
						Toast.LENGTH_LONG).show();
				SearchedNews.this.finish();

			}
		}
		
		if (requestCode == 77) {

			if (resultCode == 1) {
				Story.setTextSize(News.discrete);
			}
			if (resultCode == 0) {
				
			}
			
		}

		if (requestCode == TWITTER_AUTH) {

			if (resultCode == Activity.RESULT_OK) {

				oauthVerifier = (String) data.getExtras().get("oauth_verifier");
				if (oauthVerifier != null) {
					rt.execute();
				} else {
					// tweetB.setBackgroundResource(R.drawable.twitter_visited);
					tweeted = true;
					Toast.makeText(this,
							"There has been a mistake processing your tweet !",
							Toast.LENGTH_SHORT).show();
					if (tt.getStatus() == AsyncTask.Status.RUNNING) {
						tt.dialog.dismiss();
						tt.cancel(true);

					}

					if (rt.getStatus() == AsyncTask.Status.RUNNING) {
						rt.dialog.dismiss();
						rt.cancel(true);

					}
					if (ut.getStatus() == AsyncTask.Status.RUNNING) {
						ut.dialog.dismiss();
						ut.cancel(true);
					}
				}
			} else {
				tweeted = true;
				Toast.makeText(this,
						"There has been a mistake processing your tweet !",
						Toast.LENGTH_SHORT).show();
				if (tt.getStatus() == AsyncTask.Status.RUNNING) {
					tt.dialog.dismiss();
					tt.cancel(true);

				}

				if (rt.getStatus() == AsyncTask.Status.RUNNING) {
					rt.dialog.dismiss();
					rt.cancel(true);

				}
				if (ut.getStatus() == AsyncTask.Status.RUNNING) {
					ut.dialog.dismiss();
					ut.cancel(true);
				}

			}

		}
	}

	public boolean parseConfig(int itemIdentifier) {
		try {

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(
					"http://itweb.mobi/__itweb_pro/feed/iosv3/_load.php?section="
							+ CurrentSECTION + "&itemID=" + itemIdentifier);
			httppost.setHeader("Accept", "application/json");
			httppost.setHeader("Content-type", "application/json");

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();

		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");

			}

			result = sb.toString();

			// is.close();
			return true;
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
			return false;
		}

	}

	private class NewsFetcher extends AsyncTask<Void, Integer, Void> {
		int itemIdentifier;
		private ProgressDialog dialog;
		private Activity activity;
		private ViewItems Viewlist = null;

		public NewsFetcher(int i, Activity a) {
			activity = a;
			itemIdentifier = i;
			dialog = new ProgressDialog(activity);
			dialog.setMessage("Loading...");
			dialog.setCancelable(true);

			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					cancel(true);

					dialog.dismiss();

					finish();
				}
			});
		}

		protected void onPreExecute() {
			if(!dialog.isShowing()){
				dialog.show();
			}
			

		}

		@Override
		protected Void doInBackground(Void... params) {

			if (checkViewHolderForView() != null) {
				VI = checkViewHolderForView();
			} else {
				VI = null;
				if (parseConfig(itemIdentifier)) {
					try {
						jArray = new JSONObject(result);
						Viewlist = new ViewItems();

						Viewlist.setItemId(itemIdentifier);
						Viewlist.setCategory(CurrentSECTION);
						Viewlist.setPosition(positionX);
						bigImage = jArray.getString("storyImage");
						Viewlist.setIntroImage(bigImage);
						tITLE = jArray.getString("title");
						Viewlist.setTitle(tITLE);
						TextauthorName = jArray.getString("authorName");
						Viewlist.setJournalist(TextauthorName);
						introText = jArray.getString("introText");
						link = jArray.getString("link");
						Viewlist.setLink(link);
						tinyurl = jArray.getString("tinyurl");
						if (jArray.has("disqus")) {
							disqus = "true";
						} else {
							disqus = "false";
						}
						if (jArray.has("check_login")) {
							loginCheck = jArray.getString("check_login");
						} else {
							loginCheck = "";
						}
						storyText = jArray.getJSONArray("storyText")
								.getJSONObject(0).getString("text").toString();
						Viewlist.setText(storyText);
						Date = jArray.getString("pubDate");

					} catch (JSONException e) {
						jArray = null;
						is = null;
						Viewlist = null;
						Log.e("log_tag", "Error parsing data " + e.toString());
						Intent returnIntent = new Intent();
						returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						setResult(RESULT_CANCELED, returnIntent);

					}
				}
				if (isCancelled()) {
					jArray = null;
					is = null;
					Viewlist = null;
					if (dialog.isShowing()) {
						dialog.dismiss();
					}

				}

			}
			return null;

		}

		@Override
		protected void onProgressUpdate(Integer... values) {

		}

		@Override
		protected void onPostExecute(Void result) {
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			if (Viewlist != null) {
				VH.addItem(Viewlist);
			}
			showNews();

		}

	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent me) {
		this.detector.onTouchEvent(me);
		return super.dispatchTouchEvent(me);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent me) {
		//this.detector.onTouchEvent(me);
		return super.onTouchEvent(me);
	}

	@Override
	public void onSwipe(int direction) {
		String str = "";

		switch (direction) {

		case SimpleGestureFilter.SWIPE_RIGHT:
			str = "Swipe Right";

			if (Hlv.isShown()) {
				LinearLayout l = (LinearLayout) Hlv
						.findViewById(R.id.horisontalcontainer);

				positionX = positionX - 1;
				if (positionX < 0) {
					positionX = 0;
				}

				View w = l.getChildAt(positionX);
				if (w != null) {
					CurrentITEMID = w.getId();

					for (int k = 0; k < l.getChildCount(); k++) {
						l.getChildAt(k).setBackgroundColor(
								Color.parseColor("#ff050505"));
					}

					View oldView = l.findViewWithTag(1111);
					if (oldView != null) {
						oldView.setBackgroundColor(Color
								.parseColor("#ff050505"));
						oldView.setTag("111111111");
					}
					w.setTag(1111);
					w.setBackgroundColor(Color.parseColor("#ff376ccd"));
					int offsetX2 = ((w.getLeft() + w.getRight()) / 2)
							- (Hlv.getWidth() / 2);

					Hlv.smoothScrollTo(offsetX2, 0);
					View y = FLIP.findViewById(positionX);
					if (y != null) {
						for (int n = 0; n < FLIP.getChildCount(); n++) {
							View child = FLIP.getChildAt(n);
							if (child.getId() == positionX) {
								StoryInflated = (TextView) child
										.findViewById(R.id.summary);
								StoryInflated.setTextSize(News.discrete );
								
								FLIP.setInAnimation(animFlipInBackward);
								FLIP.setOutAnimation(animFlipOutBackward);
								FLIP.setDisplayedChild(n);

							}
						}

					} else {
						if (NF.getStatus() == AsyncTask.Status.RUNNING) {
							NF.cancel(true);
						}
						NF = new NewsFetcher(CurrentITEMID, SearchedNews.this);
						NF.execute();
					}
				}

			}
			if (singlelist.isShown()) {
				positionX = positionX - 1;
				if (positionX < 0) {
					positionX = 0;
				}
				singlelist.setSelection(positionX);

				View w = singlelist.getChildAt(0);

				if (w != null) {
					CurrentITEMID = w.getId();
					View oldView = singlelist.findViewWithTag(1111);
					if (oldView != null) {
						oldView.setBackgroundColor(Color
								.parseColor("#ff050505"));
						oldView.setTag("111111111");
					}
					w.setTag(1111);
					w.setBackgroundColor(Color.parseColor("#ff376ccd"));

				}
				View y = FLIP.findViewById(positionX);
				if (y != null) {
					for (int n = 0; n < FLIP.getChildCount(); n++) {
						View child = FLIP.getChildAt(n);
						if (child.getId() == positionX) {
							StoryInflated = (TextView) child
									.findViewById(R.id.summary);
							StoryInflated.setTextSize(News.discrete );
							
							FLIP.setInAnimation(animFlipInBackward);
							FLIP.setOutAnimation(animFlipOutBackward);
							FLIP.setDisplayedChild(n);

						}
					}
				} else {
					if (NF.getStatus() == AsyncTask.Status.RUNNING) {
						NF.cancel(true);
					}
					NF = new NewsFetcher(CurrentITEMID, SearchedNews.this);
					NF.execute();
				}

			}
			break;
		case SimpleGestureFilter.SWIPE_LEFT:
			str = "Swipe Left";

			if (Hlv.isShown()) {
				LinearLayout l = (LinearLayout) Hlv
						.findViewById(R.id.horisontalcontainer);
				positionX = positionX + 1;
				if (positionX > l.getChildCount()) {
					positionX = l.getChildCount();
				}

				View w = l.getChildAt(positionX);
				if (w != null) {

					CurrentITEMID = w.getId();

					for (int k = 0; k < l.getChildCount(); k++) {
						l.getChildAt(k).setBackgroundColor(
								Color.parseColor("#ff050505"));
					}

					View oldView = l.findViewWithTag(1111);
					if (oldView != null) {
						oldView.setBackgroundColor(Color
								.parseColor("#ff050505"));
						oldView.setTag("111111111");
					}
					w.setTag(1111);
					w.setBackgroundColor(Color.parseColor("#ff376ccd"));
					int offsetX2 = ((w.getLeft() + w.getRight()) / 2)
							- (Hlv.getWidth() / 2);

					Hlv.smoothScrollTo(offsetX2, 0);
					View y = FLIP.findViewById(positionX);
					if (y != null) {
						for (int n = 0; n < FLIP.getChildCount(); n++) {
							View child = FLIP.getChildAt(n);
							if (child.getId() == positionX) {
								StoryInflated = (TextView) child
										.findViewById(R.id.summary);
								StoryInflated.setTextSize(News.discrete);
								
								FLIP.setInAnimation(animFlipInForeward);
								FLIP.setOutAnimation(animFlipOutForeward);
								FLIP.setDisplayedChild(n);

							}
						}

					} else {
						if (NF.getStatus() == AsyncTask.Status.RUNNING) {
							NF.cancel(true);
						}
						NF = new NewsFetcher(CurrentITEMID, SearchedNews.this);
						NF.execute();
					}

				}
			}

			if (singlelist.isShown()) {
				positionX = positionX + 1;
				if (positionX > singlelist.getCount()) {
					positionX = singlelist.getCount();
				}
				singlelist.setSelection(positionX);

				View w = singlelist.getChildAt(1);

				if (w != null) {
					CurrentITEMID = w.getId();

					View oldView = singlelist.findViewWithTag(1111);
					if (oldView != null) {
						oldView.setBackgroundColor(Color
								.parseColor("#ff050505"));
						oldView.setTag("111111111");
					}
					w.setTag(1111);
					w.setBackgroundColor(Color.parseColor("#ff376ccd"));

				}

				View y = FLIP.findViewById(positionX);
				if (y != null) {
					for (int n = 0; n < FLIP.getChildCount(); n++) {
						View child = FLIP.getChildAt(n);
						if (child.getId() == positionX) {
							StoryInflated = (TextView) child
									.findViewById(R.id.summary);
							StoryInflated.setTextSize(News.discrete );
							
							FLIP.setInAnimation(animFlipInForeward);
							FLIP.setOutAnimation(animFlipOutForeward);
							FLIP.setDisplayedChild(n);

						}
					}
				} else {
					if (NF.getStatus() == AsyncTask.Status.RUNNING) {
						NF.cancel(true);
					}
					NF = new NewsFetcher(CurrentITEMID, SearchedNews.this);
					NF.execute();
				}

			}

			break;
		case SimpleGestureFilter.SWIPE_DOWN:
			str = "Swipe Down";

			break;
		case SimpleGestureFilter.SWIPE_UP:
			str = "Swipe Up";

			break;

		}

	}

	@Override
	public void onDoubleTap() {
		if (!isXLargeScreen(getApplicationContext())) {
			if (Hlv.isShown()) {
				Hlv.setVisibility(View.GONE);

			} else {
				Hlv.setVisibility(View.VISIBLE);
			}
			if (singlelist.isShown()) {
				singlelist.setVisibility(View.GONE);

			} else {
				singlelist.setVisibility(View.VISIBLE);
			}

		}
	}

	@Override
	public void onStart() {
		if (Hlv.isShown()) {

			View newsposition = (View) Hlv.findViewWithTag(1111);
			offsetX = ((newsposition.getLeft() + newsposition.getRight()) / 2)
					- (Hlv.getWidth() / 2);

			Hlv.smoothScrollTo(positionX, 0);
		} else {

			if (singlelist.isShown()) {

				singlelist.setSelection(positionX);
			}
		}

		super.onStart();
	}

	public ViewItems checkViewHolderForView() {
		if (VH != null && VH.getItemCount() > 0) {
			for (int q = 0; q < VH.getItemCount(); q++) {
				if (VH.getItem(q).getCategory().equals(CurrentSECTION)
						&& VH.getItem(q).getItemId() == CurrentITEMID) {

					return VH.getItem(q);
				}
			}
		}

		return null;
	}

	@Override
	protected void onSaveInstanceState(Bundle state) {
		super.onSaveInstanceState(state);

		state.putInt("list_state", positionX);
		state.putInt("CURRENTITEMID", CurrentITEMID);
		state.putString("CURRENTSECTION", CurrentSECTION);
		state.putString("CURRENTTITLE", titlefeed);

	}

	public boolean checkFavorite() {

		try {
			SharedPreferences myPrefs = getSharedPreferences(
					MainActivity.PREFS_FAVORITES, MODE_WORLD_READABLE);
			String prefName = myPrefs.getString("co.za.itweb.itwebpro.fav",
					"title");
			prefName = prefName.replaceAll("/", "");

			JSONArray dat;
			dat = new JSONArray(prefName);

			for (int t = 0; t < dat.length(); t++) {
				try {
					String obj = dat.getJSONObject(t).getString("title");

					if (obj.equals(newsTitleText.getText().toString())) {

						return true;

					}

				} catch (JSONException e) {
					e.printStackTrace();

				}
			}
		} catch (JSONException e1) {
			e1.printStackTrace();

		}

		return false;
	}

	public boolean addFavorite() {
		JSONArray JArray;
		try {
			SharedPreferences myPrefs = getSharedPreferences(
					MainActivity.PREFS_FAVORITES, MODE_WORLD_READABLE);
			String prefName = myPrefs.getString("co.za.itweb.itwebpro.fav",
					"title");

			if (prefName.length() > 5) {
				JArray = new JSONArray(prefName);
			} else {
				JArray = new JSONArray();
			}

			JSONObject jObjectType = new JSONObject();

			try {
				jObjectType.put("feed", CurrentSECTION);

				jObjectType.put("id", CurrentITEMID);
				jObjectType.put("title", newsTitleText.getText().toString());
				jObjectType.put("disqus", disqus);

				JArray.put(jObjectType);
				StringBuilder buf = new StringBuilder();

				buf.append(JArray).append("\n");

				SharedPreferences settings = getSharedPreferences(
						MainActivity.PREFS_FAVORITES, 0);
				SharedPreferences.Editor editor = settings.edit();
				editor.clear();

				editor.putString("co.za.itweb.itwebpro.fav", buf.toString());
				editor.commit();
				return true;
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} catch (JSONException e) {
			e.printStackTrace();

		}
		return false;

	}

	boolean checkUserLogin() {
		try {
			SharedPreferences myPrefs = getSharedPreferences(
					MainActivity.LOGIN_NAME, MODE_WORLD_READABLE);
			String prefName = myPrefs.getString("co.za.itweb.itwebpro.login",
					"login");
			prefName = prefName.replaceAll("/", "");

			JSONArray dat;
			dat = new JSONArray(prefName);

			for (int t = 0; t < dat.length(); t++) {
				try {
					String obj = dat.getJSONObject(t).getString("user");

					if (obj.length() > 0) {
						String ex = dat.getJSONObject(t).getString("expiry");

						if (compareDates(ex.substring(0, 10))) {
							return true;

						} else {
							Toast.makeText(SearchedNews.this,
									"Sorry your subscription has expired !",
									Toast.LENGTH_LONG).show();
							return false;

						}

					}

				} catch (JSONException e) {
					e.printStackTrace();

				}
			}
		} catch (JSONException e1) {
			e1.printStackTrace();

		}

		return false;

	}

	public boolean compareDates(String givenDateString) {
		Calendar cal = Calendar.getInstance();
		boolean result = false;
		Calendar currentcal = Calendar.getInstance();
		String[] separated = givenDateString.substring(0, 10).split("-");
		cal.set(Integer.parseInt(separated[0]), Integer.parseInt(separated[1]),
				Integer.parseInt(separated[2]));
		currentcal.set(currentcal.get(Calendar.YEAR),
				currentcal.get(Calendar.MONTH),
				currentcal.get(Calendar.DAY_OF_MONTH));
		if (cal.before(currentcal)) {
			System.out.print("Current date("
					+ new SimpleDateFormat("yyyy-MM-dd").format(currentcal
							.getTime()) + ") is greater than the given date "
					+ new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
			result = false;
		} else if (cal.after(currentcal)) {
			System.out.print("Current date("
					+ new SimpleDateFormat("yyyy-MM-dd").format(currentcal
							.getTime()) + ") is less than the given date "
					+ new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
			result = true;
		} else {
			System.out.print("Both date are equal.");
			result = true;
		}

		return result;
	}

	public void addTextSizeData() {
		JSONArray JArray;
		try {
			SharedPreferences myPrefs = getSharedPreferences(
					MainActivity.LOGIN_NAME, MODE_WORLD_READABLE);
			String prefName = myPrefs.getString(
					"co.za.itweb.itwebpro.textsize", "login");

			if (prefName.length() > 5) {
				JArray = new JSONArray(prefName);
			} else {
				JArray = new JSONArray();
			}

			JSONObject jObjectType = new JSONObject();

			try {
				jObjectType.put("text", News.discrete);
				JArray.put(jObjectType);
				StringBuilder buf = new StringBuilder();

				buf.append(JArray).append("\n");

				SharedPreferences settings = getSharedPreferences(
						MainActivity.LOGIN_NAME, 0);
				SharedPreferences.Editor editor = settings.edit();
				editor.clear();

				editor.putString("co.za.itweb.itwebpro.textsize",
						buf.toString());
				editor.commit();

			} catch (JSONException e) {
				e.printStackTrace();
			}
		} catch (JSONException e) {
			e.printStackTrace();

		}

	}

	// /////////////////////////////////////////////////////T W I T T E R
	// /////////////////////////////////////////////////////////////////////////////////////////////

	private boolean haveNetworkConnection() {
		haveConnectedWifi = false;
		haveConnectedMobile = false;

		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] netInfo = cm.getAllNetworkInfo();
		for (NetworkInfo ni : netInfo) {
			if (ni.getTypeName().equalsIgnoreCase("WIFI"))
				if (ni.isConnected())
					haveConnectedWifi = true;
			if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
				if (ni.isConnected())
					haveConnectedMobile = true;
		}
		return haveConnectedWifi || haveConnectedMobile;
	}

	private class TweetTask extends AsyncTask<Void, Void, Integer> {
		private SearchedNews activity;
		ProgressDialog dialog;

		public TweetTask(SearchedNews activity) {
			this.activity = activity;

		}

		protected void onPreExecute() {
			dialog = new ProgressDialog(activity);
			dialog.setMessage("Tweeting...");

			dialog.setCancelable(true);
			dialog.setMax(100);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					tt.cancel(true);
					SearchedNews.this.finish();
				}
			});
			this.dialog.show();

		}

		@Override
		protected Integer doInBackground(Void... params) {

			SharedPreferences settings = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());

			accessToken = settings.getString("twitter_access_token", null);
			accessTokenSecret = settings.getString(
					"twitter_access_token_secret", null);
			haveNetworkConnection();
			if ((haveConnectedWifi) || (haveConnectedMobile)) {

				if ((accessToken == null) || (accessTokenSecret == null)) {
					mTwitter = new TwitterFactory().getInstance();
					mRequestToken = null;
					mTwitter.setOAuthConsumer(Constants.CONSUMER_KEY,
							Constants.CONSUMER_SECRET);
					String callbackURL = getResources().getString(
							R.string.twitter_callback);
					try {
						mRequestToken = mTwitter
								.getOAuthRequestToken(callbackURL);

						return (Integer) 1;
					} catch (TwitterException e) {
						e.printStackTrace();
					}

				} else {

					return 0;
				}
			} else {

				return 0;
			}

			return 0;
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (dialog.isShowing()) {
				dialog.dismiss();
				if (result == 1) {
					setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
					startIt();
				}
			}

		}
	}

	public void startIt() {
		Intent i = new Intent(SearchedNews.this, TwitterWebviewActivity.class);
		i.putExtra("URL", mRequestToken.getAuthenticationURL());
		startActivityForResult(i, TWITTER_AUTH);

	}

	private class ResumeTask extends AsyncTask<String, Void, Integer> {
		private String oauth;
		ProgressDialog dialog;

		protected void onPreExecute() {
			oauth = oauthVerifier;
			dialog = new ProgressDialog(SearchedNews.this);
			dialog.setMessage("Tweeting...");

			dialog.setCancelable(true);
			dialog.setMax(100);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					rt.cancel(true);
					SearchedNews.this.finish();
				}
			});
			this.dialog.show();

		}

		public ResumeTask() {

		}

		@Override
		protected Integer doInBackground(String... params) {
			AccessToken at = null;

			try {
				// Pair up our request with the response
				at = mTwitter.getOAuthAccessToken(oauth);
				String theToken = at.getToken();
				// Toast.makeText(this, theToken, 10000).show();
				String theTokenSecret = at.getTokenSecret();
				// Toast.makeText(this, theTokenSecret, 10000).show();
				SharedPreferences settings = PreferenceManager
						.getDefaultSharedPreferences(getApplicationContext());
				settings = PreferenceManager
						.getDefaultSharedPreferences(getApplicationContext());
				SharedPreferences.Editor editor = settings.edit();
				editor.putString("twitter_access_token", theToken);
				editor.putString("twitter_access_token_secret", theTokenSecret);
				editor.commit();
				return (Integer) 1;

				// updateStatus();
			} catch (TwitterException e) {
				e.printStackTrace();
				return 0;
			}
		}

		@Override
		protected void onProgressUpdate(Void... values) {

		}

		@Override
		protected void onPostExecute(Integer result) {
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			if (result == 1) {
				resumeIt();
			}

		}

	}

	public void resumeIt() {
		ut.execute();

	}

	private class UpdateTask extends AsyncTask<Void, Void, Integer> {

		ProgressDialog dialog;
		private SearchedNews activity;

		protected void onPreExecute() {
			dialog = new ProgressDialog(activity);
			dialog.setMessage("Tweeting...");

			dialog.setCancelable(true);
			dialog.setMax(100);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					ut.cancel(true);
					SearchedNews.this.finish();
				}
			});
			this.dialog.show();

		}

		public UpdateTask(SearchedNews activity) {
			this.activity = activity;

		}

		@Override
		protected Integer doInBackground(Void... params) {

			SharedPreferences settings = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());
			accessToken = settings.getString("twitter_access_token", null);
			accessTokenSecret = settings.getString(
					"twitter_access_token_secret", null);

			haveNetworkConnection();
			if ((haveConnectedWifi) || (haveConnectedMobile)) {
				ConfigurationBuilder builder = new ConfigurationBuilder();
				builder.setOAuthConsumerKey(Constants.CONSUMER_KEY);
				builder.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
				builder.setOAuthAccessToken(accessToken);
				builder.setOAuthAccessTokenSecret(accessTokenSecret);
				twitter4j.conf.Configuration conf2 = builder.build();
				Twitter t = new TwitterFactory(conf2).getInstance();

				try {

					t.updateStatus(newsTitleText.getText().toString() + " "
							+ tinyurl);

					//
					return (Integer) 1;
				} catch (TwitterException e) {
					e.printStackTrace();
					return 0;

				}
			} else {

				return 0;
			}
		}

		@Override
		protected void onProgressUpdate(Void... values) {

		}

		@Override
		protected void onPostExecute(Integer result) {
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			updateIt(result);

		}
	}

	public void updateIt(Integer result) {

		if (result == 1) {
			tweeted = true;
			Toast.makeText(this, "Tweet successfully posted",
					Toast.LENGTH_SHORT).show();

		} else {
			tweeted = true;
			Toast.makeText(
					this,
					"There has been a mistake...have you already tweeted on this topic?",
					Toast.LENGTH_SHORT).show();
		}

	}

}
